import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:family_app/src/features/album/models/album_model.dart';
import 'package:family_app/src/features/auth/services/auth_service.dart';

/// 相册服务提供者
final albumServiceProvider = Provider<AlbumService>((ref) {
  // 创建专门用于相册服务的Dio实例，使用特定的基础URL
  final dio = Dio(BaseOptions(
    baseUrl: 'http://10.0.2.2:9092',  // 相册服务的特定域名
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 10),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  ));
  
  // 添加日志拦截器，方便调试
  dio.interceptors.add(LogInterceptor(
    requestBody: true,
    responseBody: true,
  ));
  
  // 添加认证拦截器
  dio.interceptors.add(InterceptorsWrapper(
    onRequest: (options, handler) {
      // 从AuthService获取token并添加到请求头
      final authService = ref.read(authServiceProvider);
      final token = authService.getToken();
      if (token != null) {
        options.headers['Authorization'] = 'Bearer $token';
      }
      return handler.next(options);
    },
  ));
  
  return AlbumService(dio);
});

/// 相册服务
class AlbumService {
  final Dio _dio;

  AlbumService(this._dio);

  /// 创建相册
  /// 
  /// 调用 http://192.168.2.141:8089/album/save 接口
  /// 返回创建的相册信息
  Future<AlbumModel?> createAlbum(CreateAlbumParam param) async {
    try {
      final response = await _dio.post(
        '/album/save',
        data: param.toJson(),
      );
      
      // 打印响应数据，便于调试
      print('创建相册响应: ${response.data}');
      
      if (response.statusCode == 200 && response.data['code'] == 200) {
        // 如果接口返回的数据结构是 {"code": 200, "data": {...}}
        final albumData = response.data['data'];
        return AlbumModel.fromJson(albumData);
      } else if (response.statusCode == 200 && response.data is Map) {
        // 如果接口直接返回相册数据
        return AlbumModel.fromJson(response.data);
      }
      
      // 创建失败
      print('创建相册失败: ${response.data}');
      return null;
    } catch (e) {
      print('创建相册异常: $e');
      return null;
    }
  }
  
  /// 获取相册列表
  Future<List<AlbumModel>> getAlbums(int userId) async {
    try {
      final response = await _dio.get(
        '/album/list',
        queryParameters: {'userId': userId},
      );
      
      if (response.statusCode == 200 && response.data['code'] == 200) {
        final List albumsData = response.data['data'];
        return albumsData.map((item) => AlbumModel.fromJson(item)).toList();
      }
      
      return [];
    } catch (e) {
      print('获取相册列表异常: $e');
      return [];
    }
  }
  
  /// 获取相册详情
  Future<AlbumModel?> getAlbumDetail(int albumId) async {
    try {
      final response = await _dio.get(
        '/album/detail/$albumId',
      );
      
      if (response.statusCode == 200 && response.data['code'] == 200) {
        final albumData = response.data['data'];
        return AlbumModel.fromJson(albumData);
      }
      
      return null;
    } catch (e) {
      print('获取相册详情异常: $e');
      return null;
    }
  }
}
